/*
 * Copyright 2011-2011 Tiago da Fonseca Frazao  All rights reserved.
 */

package mz.co.research.shared.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

/**
 * @author Tiago da Fonseca Frazao
 */
@MappedSuperclass
public abstract class AbstractEntity<T extends AbstractEntity<?>> implements
		Serializable, Comparable<T> {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID", nullable = false)
	private Long id;

	/**
	 * @return Id
	 */
	public final Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object obj) {

		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (!getClass().equals(obj.getClass())) {
			return false;
		}

		return equals((T) obj);
	}

	public boolean equals(T o) {
		return getId().equals(o.getId());
	}

	@Override
	public int hashCode() {
		return (getId() == null) ? 0 : getId().hashCode();
	}

	@Override
	public int compareTo(T o) {
		return this.getId().compareTo(o.getId());
	}

	@Override
	public String toString() {
		StringBuilder buffer = new StringBuilder("\n");
		buffer.append(getClassName());
		return buffer.append("\n  ID       : " + getId()).toString();
	}

	protected String getClassName() {
		String fqName = getClass().getName();
		return fqName.substring(fqName.lastIndexOf('.') + 1);
	}
}
